package com.mec.web.y2012.coreservlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

@WebServlet("/ShowSessionServlet")
public class ShowSessionServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final String ACCESS_COUNT = "accessCount";
       
    public ShowSessionServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html");
		
		//
		HttpSession session = request.getSession();
		String heading;
		Integer accessCount = (Integer) session.getAttribute(ACCESS_COUNT);
		if(null == accessCount){
			accessCount = 0;
			heading = "Welscome, Newcomer.";
		}else{
			heading = "Welcome Back.";
			accessCount += 1;
		}
		//
		session.setAttribute(ACCESS_COUNT, accessCount);
		
		//
		PrintWriter out = response.getWriter();
		
		response.setContentType("text/html");
		String title = "Session Tracking Example.";
		out.println(Constants.docType + ServletUtilities.headWithTitle(title) + 
				"<body><h1>" + title + "</h1><h2>Information on Your Session:</h2>" +
				"<table>"
				);
		Enumeration<String> names = session.getAttributeNames();
		while(names.hasMoreElements()){
			String name = names.nextElement();
			out.println("<tr><td>" + name + "</td><td>" + session.getAttribute(name) + "</td></tr>");
		}
		out.println("<tr><th>Previous Access : </th><th>" + accessCount +"</th></tr>");
		//
		out.println("</table></body></html>");
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
	
	private static final Logger logger = 
			Logger.getLogger(ShowSessionServlet.class);

}
